import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk, ImageDraw, ImageFont
import random
import math
import json
import os
import time

# 游戏配置
rows, cols = 9, 9
cell_width = cell_height = 80  # 稍微缩小格子，让界面更紧凑
REQUIRED_KILLS = 10

class ModernUI:
    """现代化UI组件"""
    
    @staticmethod
    def create_gradient_canvas(master, width, height, color1="#1a1a2e", color2="#16213e"):
        """创建渐变背景画布"""
        canvas = tk.Canvas(master, width=width, height=height, highlightthickness=0)
        
        # 创建渐变效果
        for i in range(height):
            ratio = i / height
            r = int(int(color1[1:3], 16) * (1 - ratio) + int(color2[1:3], 16) * ratio)
            g = int(int(color1[3:5], 16) * (1 - ratio) + int(color2[3:5], 16) * ratio)
            b = int(int(color1[5:7], 16) * (1 - ratio) + int(color2[5:7], 16) * ratio)
            color = f"#{r:02x}{g:02x}{b:02x}"
            canvas.create_line(0, i, width, i, fill=color)
        
        return canvas
    
    @staticmethod
    def create_rounded_rectangle(canvas, x1, y1, x2, y2, radius=10, **kwargs):
        """创建圆角矩形"""
        # 创建圆角矩形的路径
        points = [
            x1 + radius, y1,
            x2 - radius, y1,
            x2, y1,
            x2, y1 + radius,
            x2, y2 - radius,
            x2, y2,
            x2 - radius, y2,
            x1 + radius, y2,
            x1, y2,
            x1, y2 - radius,
            x1, y1 + radius,
            x1, y1
        ]
        return canvas.create_polygon(points, smooth=True, **kwargs)

class ResourceManager:
    """改进的资源管理器，支持默认图像生成"""
    
    def __init__(self, master):
        self.master = master
        self.images = {}
        self.default_colors = {
            "player": "#4CAF50",
            "monster": "#F44336", 
            "bullet": "#FFC107",
            "background": "#1a1a2e"
        }
    
    def create_default_image(self, size, color, text="", shape="circle"):
        """创建默认图像"""
        img = Image.new('RGBA', size, (0, 0, 0, 0))
        draw = ImageDraw.Draw(img)
        
        if shape == "circle":
            # 绘制圆形
            margin = 5
            draw.ellipse([margin, margin, size[0]-margin, size[1]-margin], 
                        fill=color, outline="white", width=2)
        elif shape == "square":
            # 绘制方形
            margin = 5
            draw.rectangle([margin, margin, size[0]-margin, size[1]-margin], 
                          fill=color, outline="white", width=2)
        
        # 添加文字
        if text:
            try:
                font = ImageFont.truetype("arial.ttf", min(size) // 4)
            except:
                font = ImageFont.load_default()
            
            bbox = draw.textbbox((0, 0), text, font=font)
            text_width = bbox[2] - bbox[0]
            text_height = bbox[3] - bbox[1]
            x = (size[0] - text_width) // 2
            y = (size[1] - text_height) // 2
            draw.text((x, y), text, fill="white", font=font)
        
        return img
    
    def load_image(self, path, size=None, default_type="player", default_text=""):
        """加载图像，如果失败则创建默认图像"""
        if path in self.images:
            return self.images[path]
        
        try:
            # 尝试加载真实图像
            full_path = os.path.join(os.path.dirname(__file__), path)
            if os.path.exists(full_path):
                img = Image.open(full_path)
                if size:
                    img = img.resize(size, Image.LANCZOS)
                self.images[path] = ImageTk.PhotoImage(img, master=self.master)
                return self.images[path]
        except Exception as e:
            print(f"加载图像失败: {path}, 使用默认图像")
        
        # 创建默认图像
        if size is None:
            size = (cell_width, cell_height)
        
        default_img = self.create_default_image(
            size, 
            self.default_colors.get(default_type, "#666666"),
            default_text,
            "circle" if default_type in ["player", "monster"] else "square"
        )
        
        self.images[path] = ImageTk.PhotoImage(default_img, master=self.master)
        return self.images[path]

class ModernHealthBar:
    """现代化的血条组件"""
    
    def __init__(self, canvas, x, y, width, height, max_health, color="#00ff00"):
        self.canvas = canvas
        self.x, self.y = x, y
        self.width, self.height = width, height
        self.max_health = max_health
        self.current_health = max_health
        self.color = color
        
        # 创建血条背景（深色）
        self.bg_bar = ModernUI.create_rounded_rectangle(
            canvas, x, y, x + width, y + height,
            radius=height//2, fill="#333333", outline=""
        )
        
        # 创建血条前景
        self.health_bar = ModernUI.create_rounded_rectangle(
            canvas, x, y, x + width, y + height,
            radius=height//2, fill=color, outline=""
        )
        
        # 创建血条边框
        self.border = ModernUI.create_rounded_rectangle(
            canvas, x-1, y-1, x + width+1, y + height+1,
            radius=height//2, fill="", outline="#ffffff", width=1
        )
        
        # 血条文字
        self.text = canvas.create_text(
            x + width // 2, y + height // 2,
            text=f"{self.current_health}/{self.max_health}",
            fill="white", font=("Arial", 8, "bold")
        )
    
    def update(self, health):
        self.current_health = max(0, health)
        percent = self.current_health / self.max_health
        
        # 更新血条颜色（根据血量变化）
        if percent > 0.6:
            color = "#00ff00"  # 绿色
        elif percent > 0.3:
            color = "#ffff00"  # 黄色
        else:
            color = "#ff0000"  # 红色
        
        # 更新血条宽度和颜色
        self.canvas.coords(self.health_bar, self.x, self.y,
                          self.x + self.width * percent, self.y + self.height)
        self.canvas.itemconfig(self.health_bar, fill=color)
        self.canvas.itemconfig(self.text, text=f"{int(self.current_health)}/{self.max_health}")
    
    def move_to(self, x, y):
        self.x, self.y = x, y
        self.canvas.coords(self.bg_bar, x, y, x + self.width, y + self.height)
        self.canvas.coords(self.health_bar, x, y, x + self.width, y + self.height)
        self.canvas.coords(self.border, x-1, y-1, x + self.width+1, y + self.height+1)
        self.canvas.coords(self.text, x + self.width // 2, y + self.height // 2)
    
    def delete(self):
        self.canvas.delete(self.bg_bar)
        self.canvas.delete(self.health_bar)
        self.canvas.delete(self.border)
        self.canvas.delete(self.text)

class Character:
    """改进的角色类"""
    
    def __init__(self, x, y, data, canvas, resources):
        self.x, self.y = x, y
        self.canvas = canvas
        self.resources = resources
        self.max_health = data["max_health"]
        self.health = self.max_health
        self.damage = data["damage"]
        self.move_speed = data.get("move_speed", 0.5)
        
        # 加载角色图像
        size = (cell_width, cell_height)
        self.image = resources.load_image(data["forms"][0], size, "player", "P")
        self.image_item = canvas.create_image(x, y, anchor="nw", image=self.image)
        
        # 创建现代化血条
        self.health_bar = ModernHealthBar(canvas, x, y - 20, cell_width, 12, self.max_health)
        
        # 战斗状态
        self.is_alive = True
        self.grade = 1
        self.exp = 0
        self.exp_to_level = 100
        
        # 移动绑定
        self.keys = {"Up": False, "Down": False, "Left": False, "Right": False,
                     "w": False, "s": False, "a": False, "d": False}
        
        # 等级显示
        self.level_text = canvas.create_text(
            x + cell_width // 2, y + cell_height + 10,
            text=f"Lv.{self.grade}", fill="#00ffff", font=("Arial", 10, "bold")
        )
    
    def move(self, event):
        if not self.is_alive:
            return
        
        key = event.keysym
        if key.lower() == 'w': key = "Up"
        if key.lower() == 's': key = "Down"
        if key.lower() == 'a': key = "Left"
        if key.lower() == 'd': key = "Right"
        
        if key in self.keys:
            self.keys[key] = True
            
            dx, dy = 0, 0
            if self.keys["Up"]: dy -= 1
            if self.keys["Down"]: dy += 1
            if self.keys["Left"]: dx -= 1
            if self.keys["Right"]: dx += 1
            
            new_x = self.x + dx * cell_width * self.move_speed
            new_y = self.y + dy * cell_height * self.move_speed
            
            if 0 <= new_x < (cols - 1) * cell_width and 0 <= new_y < (rows - 1) * cell_height:
                self.x, self.y = new_x, new_y
                self.canvas.coords(self.image_item, self.x, self.y)
                self.health_bar.move_to(self.x, self.y - 20)
                self.canvas.coords(self.level_text, self.x + cell_width // 2, self.y + cell_height + 10)
    
    def stop_move(self, event):
        key = event.keysym
        if key.lower() == 'w': key = "Up"
        if key.lower() == 's': key = "Down"
        if key.lower() == 'a': key = "Left"
        if key.lower() == 'd': key = "Right"
        
        if key in self.keys:
            self.keys[key] = False
    
    def take_damage(self, damage):
        self.health -= damage
        self.health_bar.update(self.health)
        
        # 受伤闪烁效果
        self.canvas.itemconfig(self.image_item, state="hidden")
        self.canvas.after(100, lambda: self.canvas.itemconfig(self.image_item, state="normal"))
        
        if self.health <= 0:
            self.die()
    
    def die(self):
        self.is_alive = False
        self.canvas.itemconfig(self.image_item, state="hidden")
        self.health_bar.delete()
        self.canvas.delete(self.level_text)
    
    def gain_exp(self, exp):
        self.exp += exp
        while self.exp >= self.exp_to_level:
            self.level_up()
    
    def level_up(self):
        self.exp -= self.exp_to_level
        self.grade += 1
        self.exp_to_level = int(self.exp_to_level * 1.5)
        self.max_health = int(self.max_health * 1.2)
        self.health = self.max_health
        self.damage = int(self.damage * 1.2)
        
        # 重新创建血条和等级显示
        self.health_bar.delete()
        self.canvas.delete(self.level_text)
        self.health_bar = ModernHealthBar(self.canvas, self.x, self.y - 20, cell_width, 12, self.max_health)
        self.level_text = self.canvas.create_text(
            self.x + cell_width // 2, self.y + cell_height + 10,
            text=f"Lv.{self.grade}", fill="#00ffff", font=("Arial", 10, "bold")
        )

class Boss:
    """改进的怪物类"""
    
    def __init__(self, x, y, level, game_data, canvas, resources):
        self.x, self.y = x, y
        self.level = level
        self.canvas = canvas
        self.resources = resources
        
        # 从配置中获取属性
        monsters = game_data["monsters"]
        self.max_health = monsters["health"][min(level, len(monsters["health"]) - 1)]
        self.health = self.max_health
        self.damage = monsters["damage"][min(level, len(monsters["damage"]) - 1)]
        self.move_speed = monsters.get("move_speed", [0.3])[min(level, len(monsters.get("move_speed", [0.3])) - 1)]
        self.exp = monsters["exp"][min(level, len(monsters["exp"]) - 1)]
        
        # 加载怪物图像
        size = (cell_width, cell_height)
        self.image = resources.load_image(monsters["forms"][0], size, "monster", f"M{level+1}")
        self.image_item = canvas.create_image(x, y, anchor="nw", image=self.image)
        
        # 创建现代化血条
        self.health_bar = ModernHealthBar(canvas, x, y - 20, cell_width, 12, self.max_health)
        
        # 战斗状态
        self.is_alive = True
        
        # 等级显示
        self.level_text = canvas.create_text(
            x + cell_width // 2, y + cell_height + 10,
            text=f"Lv.{level+1}", fill="#ff6666", font=("Arial", 10, "bold")
        )
    
    def move_randomly(self):
        if not self.is_alive:
            return
        
        if random.random() < 0.03:  # 降低移动概率
            dx, dy = random.choice([(-1, 0), (1, 0), (0, -1), (0, 1)])
            new_x = self.x + dx * cell_width * self.move_speed
            new_y = self.y + dy * cell_height * self.move_speed
            
            if 0 <= new_x < (cols - 1) * cell_width and 0 <= new_y < (rows - 1) * cell_height:
                self.x, self.y = new_x, new_y
                self.canvas.coords(self.image_item, self.x, self.y)
                self.health_bar.move_to(self.x, self.y - 20)
                self.canvas.coords(self.level_text, self.x + cell_width // 2, self.y + cell_height + 10)
    
    def take_damage(self, damage):
        self.health -= damage
        self.health_bar.update(self.health)
        
        # 受伤闪烁效果
        self.canvas.itemconfig(self.image_item, state="hidden")
        self.canvas.after(100, lambda: self.canvas.itemconfig(self.image_item, state="normal"))
        
        if self.health <= 0:
            self.die()
    
    def die(self):
        self.is_alive = False
        self.canvas.delete(self.image_item)
        self.health_bar.delete()
        self.canvas.delete(self.level_text)

class Zidan:
    """改进的子弹类"""
    
    def __init__(self, x, y, dir_x, dir_y, damage, game_data, canvas, resources):
        self.x, self.y = x, y
        self.dir_x, self.dir_y = dir_x, dir_y
        self.speed = game_data["bullet"]["speed"]
        self.damage = damage
        self.canvas = canvas
        self.resources = resources
        
        # 创建子弹图像
        size = (cell_width // 4, cell_height // 4)
        bullet_form = game_data["bullet"].get("form", "images/bullet.png")
        self.image = resources.load_image(bullet_form, size, "bullet", "•")
        self.image_item = canvas.create_image(x, y, anchor="center", image=self.image)
        
        self.is_alive = True
    
    def move(self):
        self.x += self.dir_x * self.speed
        self.y += self.dir_y * self.speed
        self.canvas.coords(self.image_item, self.x, self.y)
        
        if not (0 <= self.x <= cols * cell_width and 0 <= self.y <= rows * cell_height):
            self.is_alive = False
            self.canvas.delete(self.image_item)
    
    def attack(self, bosses):
        if not self.is_alive:
            return False
        
        for boss in bosses:
            if not boss.is_alive:
                continue
            
            if (abs(self.x - (boss.x + cell_width // 2)) < cell_width // 2 and
                    abs(self.y - (boss.y + cell_height // 2)) < cell_height // 2):
                boss.take_damage(self.damage)
                self.is_alive = False
                self.canvas.delete(self.image_item)
                return True
        return False

class FightGame:
    """现代化的战斗游戏主类"""
    
    def __init__(self, json_path, parent=None, fullscreen=False):
        self.parent = parent
        self.root = tk.Toplevel(parent) if parent else tk.Tk()
        self.root.title("战斗系统 - 现代化版本")
        
        if fullscreen:
            # 全屏模式
            self.root.attributes("-fullscreen", True)
            self.screen_width = self.root.winfo_screenwidth()
            self.screen_height = self.root.winfo_screenheight()
            
            # 调整游戏区域大小以适应全屏
            global cell_width, cell_height
            cell_width = cell_height = min(self.screen_width // (cols + 2), self.screen_height // (rows + 2))
        else:
            # 窗口模式
            window_width = cols * cell_width + 200  # 增加侧边栏空间
            window_height = rows * cell_height + 100
            self.root.geometry(f"{window_width}x{window_height}")
            self.root.resizable(False, False)
            self.screen_width = window_width
            self.screen_height = window_height
        
        # 居中显示
        if parent and not fullscreen:
            self.root.transient(parent)
            self.root.grab_set()
        
        # 加载游戏数据
        self.game_data = self.load_game_data(json_path)
        
        # 初始化资源管理器
        self.resources = ResourceManager(self.root)
        
        # 创建主界面
        self.create_ui()
        
        # 初始化游戏状态
        self.init_game_state()
        
        # 绑定事件
        self.bind_events()
        
        # 战斗结果
        self.result = None
        
        # 开始游戏循环
        self.update()
        
        if not parent:
            self.root.mainloop()
    
    def create_ui(self):
        """创建现代化UI"""
        # 创建主框架
        main_frame = tk.Frame(self.root, bg="#1a1a2e")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建游戏区域
        game_frame = tk.Frame(main_frame, bg="#1a1a2e")
        game_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 创建游戏画布
        self.canvas = tk.Canvas(game_frame, width=cols * cell_width, height=rows * cell_height,
                               highlightthickness=0)
        self.canvas.pack()
        
        # 尝试加载背景图片
        try:
            bg_path = self.game_data.get("background", "images/background.jpg")
            self.background = self.resources.load_image(bg_path, (cols * cell_width, rows * cell_height))
            self.canvas.create_image(0, 0, anchor="nw", image=self.background)
        except:
            # 如果背景加载失败，使用渐变背景
            self.canvas = ModernUI.create_gradient_canvas(
                game_frame, cols * cell_width, rows * cell_height
            )
            self.canvas.pack()
        
        # 创建侧边栏
        self.create_sidebar(main_frame)
    
    def create_sidebar(self, main_frame):
        """创建侧边栏"""
        sidebar = tk.Frame(main_frame, bg="#16213e", width=180)
        sidebar.pack(side=tk.RIGHT, fill=tk.Y, padx=10, pady=10)
        sidebar.pack_propagate(False)
        
        # 标题
        title_label = tk.Label(sidebar, text="战斗状态", 
                              font=("微软雅黑", 16, "bold"),
                              bg="#16213e", fg="#ffffff")
        title_label.pack(pady=10)
        
        # 击杀计数
        self.kill_frame = tk.Frame(sidebar, bg="#16213e")
        self.kill_frame.pack(fill=tk.X, padx=10, pady=5)
        
        tk.Label(self.kill_frame, text="击杀进度:", 
                font=("微软雅黑", 12), bg="#16213e", fg="#ffffff").pack(anchor=tk.W)
        
        self.kill_progress = ttk.Progressbar(self.kill_frame, length=150, mode='determinate')
        self.kill_progress.pack(pady=5)
        
        self.kill_label = tk.Label(self.kill_frame, text="0/10", 
                                  font=("微软雅黑", 14, "bold"),
                                  bg="#16213e", fg="#00ff00")
        self.kill_label.pack()
        
        # 玩家状态
        player_frame = tk.Frame(sidebar, bg="#16213e")
        player_frame.pack(fill=tk.X, padx=10, pady=10)
        
        tk.Label(player_frame, text="玩家状态:", 
                font=("微软雅黑", 12), bg="#16213e", fg="#ffffff").pack(anchor=tk.W)
        
        self.player_health_label = tk.Label(player_frame, text="血量: 100/100", 
                                           font=("微软雅黑", 10), bg="#16213e", fg="#00ff00")
        self.player_health_label.pack(anchor=tk.W)
        
        self.player_level_label = tk.Label(player_frame, text="等级: 1", 
                                          font=("微软雅黑", 10), bg="#16213e", fg="#00ffff")
        self.player_level_label.pack(anchor=tk.W)
        
        self.player_damage_label = tk.Label(player_frame, text="攻击: 10", 
                                           font=("微软雅黑", 10), bg="#16213e", fg="#ff6666")
        self.player_damage_label.pack(anchor=tk.W)
        
        # 控制说明
        control_frame = tk.Frame(sidebar, bg="#16213e")
        control_frame.pack(fill=tk.X, padx=10, pady=10)
        
        tk.Label(control_frame, text="操作说明:", 
                font=("微软雅黑", 12), bg="#16213e", fg="#ffffff").pack(anchor=tk.W)
        
        controls = [
            "WASD/方向键: 移动",
            "鼠标点击: 射击",
            "Q: 退出战斗"
        ]
        
        for control in controls:
            tk.Label(control_frame, text=control, 
                    font=("微软雅黑", 9), bg="#16213e", fg="#cccccc").pack(anchor=tk.W)
    
    def init_game_state(self):
        """初始化游戏状态"""
        # 创建玩家角色
        self.player = Character(
            cell_width, cell_height,
            self.game_data["player"],
            self.canvas, self.resources
        )
        
        # 创建怪物
        self.bosses = []
        for _ in range(3):
            self.spawn_boss()
        
        # 创建子弹列表
        self.bullets = []
        
        # 击杀计数
        self.kill_count = 0
        self.update_ui()
    
    def update_ui(self):
        """更新UI显示"""
        # 更新击杀进度
        progress = (self.kill_count / REQUIRED_KILLS) * 100
        self.kill_progress['value'] = progress
        self.kill_label.config(text=f"{self.kill_count}/{REQUIRED_KILLS}")
        
        # 更新玩家状态
        if self.player and self.player.is_alive:
            self.player_health_label.config(text=f"血量: {int(self.player.health)}/{self.player.max_health}")
            self.player_level_label.config(text=f"等级: {self.player.grade}")
            self.player_damage_label.config(text=f"攻击: {self.player.damage}")
    
    def load_game_data(self, json_path):
        """加载游戏数据"""
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            print(f"加载战斗配置失败: {e}")
            return {
                "player": {
                    "forms": ["images/player.png"],
                    "max_health": 100,
                    "damage": 10,
                    "move_speed": 0.5
                },
                "monsters": {
                    "health": [100, 150, 200],
                    "damage": [10, 15, 20],
                    "move_speed": [0.3, 0.4, 0.5],
                    "exp": [50, 100, 150],
                    "forms": ["images/monster.png"]
                },
                "bullet": {
                    "speed": 5,
                    "form": "images/bullet.png"
                },
                "background": "images/background.jpg"
            }
    
    def spawn_boss(self):
        """生成怪物"""
        x = random.randint(1, cols - 2) * cell_width
        y = random.randint(1, rows - 2) * cell_height
        
        boss_level = min(self.player.grade, len(self.game_data["monsters"]["health"]) - 1)
        boss = Boss(x, y, boss_level, self.game_data, self.canvas, self.resources)
        self.bosses.append(boss)
    
    def bind_events(self):
        """绑定事件"""
        self.root.bind("<KeyPress>", self.on_key_press)
        self.root.bind("<KeyRelease>", self.on_key_release)
        self.canvas.bind("<Button-1>", self.on_canvas_click)
        self.root.bind("<q>", self.close_window)
        self.root.focus_set()
    
    def on_key_press(self, event):
        if self.player:
            self.player.move(event)
    
    def on_key_release(self, event):
        if self.player:
            self.player.stop_move(event)
    
    def on_canvas_click(self, event):
        if not self.player or not self.player.is_alive:
            return
        
        dx = event.x - (self.player.x + cell_width // 2)
        dy = event.y - (self.player.y + cell_height // 2)
        if dx == 0 and dy == 0:
            return
        
        length = math.sqrt(dx * dx + dy * dy)
        dir_x, dir_y = dx / length, dy / length
        
        bullet = Zidan(
            self.player.x + cell_width // 2,
            self.player.y + cell_height // 2,
            dir_x, dir_y,
            self.player.damage,
            self.game_data,
            self.canvas,
            self.resources
        )
        self.bullets.append(bullet)
    
    def check_collisions(self):
        """检查碰撞"""
        if self.player and self.player.is_alive:
            player_center = (self.player.x + cell_width // 2, self.player.y + cell_height // 2)
            for boss in self.bosses:
                if boss.is_alive:
                    boss_center = (boss.x + cell_width // 2, boss.y + cell_height // 2)
                    distance = math.sqrt(
                        (player_center[0] - boss_center[0]) ** 2 +
                        (player_center[1] - boss_center[1]) ** 2
                    )
                    if distance < cell_width * 0.7:
                        self.player.take_damage(boss.damage)
                        boss.take_damage(self.player.damage)
    
    def update(self):
        """游戏主循环"""
        # 清理已死亡的怪物
        for boss in self.bosses[:]:
            if not boss.is_alive:
                self.bosses.remove(boss)
                self.player.gain_exp(boss.exp)
                self.kill_count += 1
                self.update_ui()
                
                if self.kill_count >= REQUIRED_KILLS:
                    self.result = "victory"
                    self.show_result("任务完成!")
                    return
                
                if len(self.bosses) < 3:
                    self.spawn_boss()
        
        # 更新子弹
        for bullet in self.bullets[:]:
            bullet.move()
            if bullet.attack(self.bosses) or not bullet.is_alive:
                self.bullets.remove(bullet)
        
        # 更新怪物移动
        for boss in self.bosses:
            if boss.is_alive:
                boss.move_randomly()
        
        # 检查碰撞
        self.check_collisions()
        
        # 检查战斗结果
        if self.player and not self.player.is_alive and self.result is None:
            self.result = "defeat"
            self.show_result("战斗失败!")
        
        # 继续游戏循环
        self.root.after(30, self.update)
    
    def show_result(self, text):
        """显示战斗结果"""
        # 创建半透明覆盖层
        overlay = tk.Canvas(self.canvas, width=cols * cell_width, height=rows * cell_height,
                           bg="black", highlightthickness=0)
        overlay.place(x=0, y=0)
        overlay.configure(bg="black")
        
        # 创建结果窗口
        result_width = 400
        result_height = 200
        x = (cols * cell_width - result_width) // 2
        y = (rows * cell_height - result_height) // 2
        
        # 背景
        ModernUI.create_rounded_rectangle(
            overlay, x, y, x + result_width, y + result_height,
            radius=20, fill="#1a1a2e", outline="#00ff00", width=3
        )
        
        # 结果文字
        overlay.create_text(
            cols * cell_width // 2, rows * cell_height // 2 - 20,
            text=text, fill="#00ff00", font=("微软雅黑", 24, "bold")
        )
        
        # 提示文字
        overlay.create_text(
            cols * cell_width // 2, rows * cell_height // 2 + 40,
            text="按Q键退出", fill="#ffffff", font=("微软雅黑", 16)
        )
    
    def close_window(self, event=None):
        """关闭窗口"""
        if self.parent:
            self.root.destroy()
        else:
            self.root.quit()

# 主程序入口
if __name__ == "__main__":
    FightGame("dialogues/战斗关卡/第一关.json")
